package kamikaze.service.member;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import kamikaze.entity.User;
import kamikaze.entity.User.CardType;
import kamikaze.support.HttpMethod;
import kamikaze.support.MessageView;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;
import kamikaze.support.StringUtil;

@ServiceConfig(path = "user.register", method = HttpMethod.POST)
public class UserRegistrationService implements Service {

	@Override
	public String serve(ServiceContext ctx) throws Exception {
		ArrayList<String> error = new ArrayList<String>();
		HttpServletRequest req = ctx.getRequest();

		String cardName = req.getParameter("cardName");
		error.add(StringUtil.ensureNotBlank(cardName, "card name"));

		String username = req.getParameter("loginId");
		error.add(StringUtil.ensureMatch(username,
				StringUtil.PATTERN_ALPHANUMERIC, "username needs to be alpha numeric"));

		String password = req.getParameter("password");
		error.add(StringUtil.ensureNotBlank(password, "password"));

		String email = req.getParameter("email");
		error.add(StringUtil.ensureNotBlank(email, "email"));

		String name = req.getParameter("name");
		error.add(StringUtil.ensureNotBlank(name, "name"));

		String cardNumber = req.getParameter("cardNumber");
		error.add(StringUtil.ensureMatch(cardNumber,
				StringUtil.PATTERN_ALPHANUMERIC, "username needs to be alpha numeric"));

		while (error.remove(null)) {
			// do nothing
		}

		if (!error.isEmpty()) {
			throw new ServiceException(error.toString());
		}

		final User user = new User();

		user.setCardName(cardName);
		user.setCardNumber(cardNumber);
		user.setCardType(CardType.valueOf(req.getParameter("cardType")));
		user.setExpiredDate(new SimpleDateFormat("mmyyyy").parse(req.getParameter("expiredDate")));

		user.setLoginId(username);
		user.setPassword(StringUtil.encrypt(password));

		user.setName(name);
		user.setEmail(email);

		user.setSuspended(true);

		EntityManager em = ctx.getEntityManager();

		Number count = (Number) em.createQuery("select count(u) from User u where u.loginId = :loginId")
				.setParameter("loginId", user.getLoginId())
				.getSingleResult();

		if (count.intValue() != 0) {
			throw new ServiceException("login id is taken");
		}

		em.persist(user);

		return MessageView.from(ctx)
				.setMessage("Registration successful")
				.setNextURL("/logout.jsp")
				.getViewName();
	}

}
